/**
 * Created by thomas on 2017/6/19.
 */
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');//加前缀
var cssgrace  = require('cssgrace');//自己出现兼容的css
var cssnext  = require('gulp-cssnext');//继续是兼容的css
var connect = require('gulp-connect');
var precss = require("precss");
var sprites = require('postcss-sprites');
var htmlmin = require('gulp-htmlmin');
var minify=require('gulp-minify-css');
var  proxy=require('http-proxy-middleware');
// var proxy = require('http-proxy-middleware')
/**
 * Configure proxy middleware
 */
// var jsonPlaceholderProxy = proxy({
//     target: 'http://jsonplaceholder.typicode.com',
//     changeOrigin: true,             // for vhosted sites, changes host header to match to target's host
//     logLevel: 'debug'
// })

var options = {
    matchPattern: "*.css" // process only css
};
var processors = [
    autoprefixer,
    precss
    // sprites({
    //     source: './static/img',
    //     output: "./dest"
    // })
];

gulp.task('watch', function(){
    gulp.watch('./css/*.css', ['min']);
    gulp.watch('./js/*.js', ["html"]);
    gulp.watch('./*.html', ['html']);
    gulp.watch('./templates/*.hbs', ['html']);
});
gulp.task("min",function () {
    return  gulp.src('./common/*.css')
    .pipe(minify())
    .pipe(gulp.dest('libs/dist/css')) //输出文件夹
    .pipe(connect.reload())
})
gulp.task('autoprefixer', function () {
    var postcss      = require('gulp-postcss');
    var sourcemaps   = require('gulp-sourcemaps');
    var autoprefixer = require('autoprefixer');

    return  gulp.src('./static/css/*.css')
        .pipe(sourcemaps.init())
        .pipe(postcss(processors))
        .on('error', function(err) {
            console.log('Less Error!', err.message);
            this.end();
        })
        .pipe(cssnext({"browserslist": [
            "> 1%",
            "last 4 versions"
        ]}))
        .on('error', function(err) {
            console.log('Less Error!', err.message);
            this.end();
        })
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dest/css'))
});

gulp.task('connect',function(){
    connect.server({
        root:'./',
        port:8003,
        ip:'localhost',
        livereload:true,
        middleware: function(connect, opt) {
            return [
                proxy('/api', {
                    target: 'http://localhost:8002/',
                    changeOrigin:true
                }),
                proxy('/easy_stock',{
                    target: 'http://easy-stock.webmocking.com/',
                    changeOrigin:true
                })
            ]
        }
    })
});

gulp.task('html', function(){
    gulp.src('./*.html')
        .pipe(connect.reload());
});

gulp.task('default', ['watch', 'autoprefixer',"connect"]);